<template>
    <div id="brand_edit" class="Row_content" style="width:500px;">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="110">
        <FormItem label="品牌名称：" prop="brandName">
          <Input v-model="formValidate.brandName" placeholder="请输入" class='input-wid' :maxlength='20' @on-keyup='filterName' @on-blur="filterName" @on-change='changeBrandName'></Input>
        </FormItem>
        <FormItem label="品牌首字母：" prop="initial">
          <!-- <Input v-model="formValidate.initial" placeholder="填写品牌名称后自动生成" class='input-wid' @on-keyup='filterBrand' @on-blur="filterBrand"></Input> -->
          <div style="display: flex;width: 460px">
            <Input v-model="formValidate.initial" placeholder="填写品牌名称后自动生成" style="width: 260px;" :maxlength="1" @on-keyup='filterBrand' @on-blur="filterBrand"></Input>
            <p style="width: 120px;margin-left: 10px">如有不符,请手工修改</p>
          </div>
        </FormItem>
        <FormItem label="上传图片：" class="loadimg-form" prop="logo">
          <Row type="flex" align="top">
            <Col>
            <Upload ref="upload"
              :format="['jpg','png']"
              :max-size="50"
              :on-success="handleSuccess"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              type="drag"
              :action="$config.uploadImg"
              :show-upload-list="false"
              style="display: inline-block;width:96px">
              <img :src="formValidate.logo ? formValidate.logo : defaultUrl"
                style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                alt="" />
            </Upload>
              <p v-if="formValidate.logo" class="replace_tit" @click="delHeadImage">删除</p>
            </Col>
            <Col>
            <div style="width:132px;height:72px;line-height:18px;color: #464C5B;margin-left:16px">
              <p>支持格式：.jpg、.png</p>
              <p>规格：235*110px</p>
              <p>大小：≤50K</p>
            </div>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="是否显示：" prop='isShow'>
          <RadioGroup v-model="formValidate.isShow">
            <Radio label="1" >显示</Radio>
            <Radio label="0" style="margin-left: 25px">隐藏</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="品牌简介：" style="width: 450px" prop='remark'>
          <Input v-model="formValidate.brandDesc"
            type="textarea" style="width:320px"
            :autosize="{ minRows: 5, maxRows: 8 }"
            :maxlength="200"
            placeholder="请输入内容"></Input>
            <p style="text-align: right;width: 320px">{{desc}}/200</p>
        </FormItem>
        <FormItem>
          <Button type="primary" class="btn" @click="handleSubmit">确定</Button>
          <Button class="btn" style="margin-left: 24px" @click="handleReset">取消</Button>
        </FormItem>
      </Form>
    </div>
  </template>

<script>
import { detailBrand, editBrand } from '@/api/commondity/index'
import { pinyin } from '@/libs/pinYin.js'
import { routeEqual } from '@/libs/util'
export default {
  name: 'brand_edit',
  computed: {
    desc () {
      return this.formValidate.brandDesc.length
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.brandId !== to.params.id) {
        vm.brandId = to.params.id
        vm.getDetail()
      }
    })
  },
  watch: {
    'formValidate.initial' (val) {
      if (val) {
        this.formValidate.initial = this.formValidate.initial.toUpperCase()
      }
    }
  },
  data () {
    return {
      submitLock: false,
      brandId: '',
      defaultUrl: require('@/assets/images/add.png'),
      brandInitialList: [],
      formValidate: {
        brandName: '',
        initial: '',
        logo: '',
        brandDesc: '',
        isShow: '1'
      },
      ruleValidate: {
        brandName: { required: true, message: '请填写品牌名称', trigger: 'blur' },
        initial: { required: true, message: '填写品牌名称后自动生成', trigger: 'change' },
        logo: { required: true, message: '请上传品牌Logo', trigger: 'change' },
        isShow: { required: true, message: '请选择是否显示', trigger: 'change' }
      }
    }
  },
  methods: {
    changeBrandName () {
      this.formValidate.brandName = this.formValidate.brandName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/, '')
      if (this.formValidate.brandName) {
        this.formValidate.initial = pinyin.getCamelChars(this.formValidate.brandName)[0].toUpperCase()
      } else {
        this.formValidate.initial = ''
      }
    },
    filterName () {
      this.formValidate.brandName = this.formValidate.brandName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/, '')
    },
    filterBrand () {
      this.formValidate.initial = this.formValidate.initial.replace(/[^A-Za-z0-9]/, '')
    },
    handleSubmit () {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          if (this.submitLock) {
            return
          }
          this.submitLock = true
          editBrand({
            ...this.formValidate,
            merchantId: this.$store.state.user.merchantId,
            seq: '',
            updater: this.$store.state.user.userId,
            updaterName: this.$store.state.user.userName,
            brandId: this.brandId
          }).then(res => {
            this.submitLock = false
            if (res.data.status === 200) {
              this.$Message.success('编辑成功!')
              this.handleReset()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          }).catch(err => {
            this.submitLock = false
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'brand_list'
        })
      })
    },
    getSize (url) {
      var img = new Image()
      img.src = url
      var that = this
      img.onload = function () {
        if (img.width === 235 && img.height === 110) {
          // 此处处理图片名称
          that.formValidate.logo = url
          that.$refs.formValidate.validate()
        } else {
          that.formValidate.logo = ''
          that.$Notice.warning({
            title: '上传的图片规格不符',
            duration: 1.5
          })
        }
      }
    },
    handleSuccess (response, file, fileList) {
      if (response.full_img_url) {
        this.getSize(response.full_img_url)
      }
    },
    handleFormatError () {
      this.$Message.warning('上传的图片格式错误')
    },
    handleMaxSize () {
      this.$Message.warning('上传的图片大小不能超过50k')
    },
    delHeadImage () {
      this.formValidate.logo = ''
    },
    getDetail () {
      detailBrand({
        merchantId: this.$store.state.user.merchantId,
        brandId: this.brandId
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.formValidate = {
            brandName: result.data.brandName,
            initial: result.data.initial,
            logo: result.data.logo,
            brandDesc: result.data.brandDesc,
            isShow: result.data.isShow + ''
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    this.brandId = this.$route.params.id
    this.getDetail()
  }
}
</script>

  <style lang="less">
  #brand_edit{
    .btn{width: 100px}
    .replace_tit {
      width: 100%;
      position: absolute;
      left: 0;
      bottom: 14px;
      opacity: .6;
      filter: alpha(opacity=60);
      background: #ed4014;
      color: #fff;
      text-align: center;
    }
  }
  </style>
